

from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from meiduo_admin.serializers.spu_serializers import *
from meiduo_admin.utils.pages import MyPage
from goods.models import GoodsCategory
from meiduo_admin.serializers.sku_serializers import GoodsCategorySimpleSeializer


# 序列化返回一级分类
# GET + goods/channel/categories/ = self.list
# 序列化返回二级分类
# GET + goods/channel/categories/(?P<pk>\d+)/ = self.list
# 根据不同的请求，实现操作不同的查询集
class SPUCategorySimpleView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategorySimpleSeializer

    def get_queryset(self):
        # 0、尝试着获取路径pk参数
        cat_id = self.kwargs.get('pk')
        if cat_id:
            # 1、如果请求路径中有pk(一级、二级)分类主键，那么
            # 就过滤出子级分类序列化返回
            return self.queryset.filter(parent_id=cat_id)
        else:
            # 2、如果请求路径中没有pk，那么过滤出一级分类序列化返回
            return self.queryset.filter(parent=None)


class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUModelSerializer

    pagination_class = MyPage

    def get_queryset(self):
        # 重写get_queryset可以实现，根据不同的接口，使用不同的查询集

        # self.action: 代表当前请求的视图方法名字！
        if self.action == "simple_brand":
            # 如果是处理brand相关
            return Brand.objects.all()

        # 如果是处理spu相关的
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all()


    def get_serializer_class(self):
        # 重写get_serializer_class可以实现，根据不同的接口，采用不同的序列化器
        if self.action == 'simple_brand':
            return BrandSimpleSerializer
        return self.serializer_class


    def simple_brand(self, request):
        brands = self.get_queryset()
        serializer = self.get_serializer(brands, many=True)
        return Response(serializer.data)